<template>
  <div class="captcha-container">
    <div class="captcha-image" @click="refreshCaptcha">
      <img v-if="captchaImage" :src="captchaImage" alt="验证码" />
      <span v-else>点击获取验证码</span>
    </div>
    <div class="captcha-input">
      <input
        v-model="captchaCode"
        type="text"
        placeholder="请输入验证码"
        maxlength="6"
      />
    </div>
  </div>
</template>

<script>
import { captchaApi } from '../services/api';

export default {
  name: 'Captcha',
  data() {
    return {
      captchaId: '',
      captchaImage: '',
      captchaCode: ''
    };
  },
  methods: {
    async refreshCaptcha() {
      try {
        const response = await captchaApi.getCaptchaImage();
        this.captchaId = response.id;
        this.captchaImage = response.image;
        this.captchaCode = '';
      } catch (error) {
        console.error('获取验证码失败:', error);
      }
    },
    async verifyCaptcha() {
      if (!this.captchaId || !this.captchaCode) {
        throw new Error('请先获取并输入验证码');
      }
      try {
        await captchaApi.verifyCaptcha({
          captchaId: this.captchaId,
          captchaCode: this.captchaCode
        });
        return true;
      } catch (error) {
        console.error('验证码验证失败:', error);
        this.refreshCaptcha();
        throw error;
      }
    }
  },
  mounted() {
    this.refreshCaptcha();
  }
};
</script>

<style scoped>
.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
}
.captcha-image {
  width: 120px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  cursor: pointer;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}
.captcha-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.captcha-input input {
  width: 120px;
  height: 40px;
  padding: 0 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}
</style>